package com.aurora.app.service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.aurora.app.dao.CategoryThingDao;
import com.aurora.app.dao.LocationDao;
import com.aurora.app.dao.PayOrderDao;
import com.aurora.app.dao.ThingImageDao;
import com.aurora.app.dao.ThingDao;
import com.aurora.app.dao.UserDao;
import com.aurora.app.entity.CategoryThing;
import com.aurora.app.entity.Location;
import com.aurora.app.entity.PayOrder;
import com.aurora.app.entity.Thing;
import com.aurora.app.entity.ThingImage;
import com.aurora.app.entity.User;
import com.aurora.app.enums.FakeDelete;
import com.aurora.app.enums.PayState;
import com.aurora.base.dao.BaseDao;
import com.aurora.base.dto.Order;
import com.aurora.base.dto.QueryResult;
import com.aurora.base.service.BaseService;
import com.aurora.base.util.StringConvertDate;

/**
 * 用户出售物品表
 * @author Administrator
 *
 */
@Service
public class ThingService extends BaseService<Thing> {
	private final Logger LOG = LoggerFactory.getLogger(this.getClass());
	@Resource
	private ThingDao baseDao;
	@Resource
	private CategoryThingDao  categoryThingDao;
	@Resource 
	private ThingImageDao thingImageDao;
	@Resource
	private LocationDao locationDao;
	@Resource
	private UserDao userDao;
	@Resource
	private PayOrderDao payOrderDao;
	
	
	@Override
	public BaseDao<Thing> getBaseDao() {
		// TODO Auto-generated method stub
		return this.baseDao;
	}

	/**
	 * 获取所有的物品列表
	 * @param request
	 * @return
	 */
	public List<Thing> getListWithPages(HttpServletRequest request) {
		Order order = new Order();
		
		//获取方式  0 为最新 1为关注度最高
		String type = request.getParameter("type");
		
		if(StringUtils.isNotBlank(type)){
			if(type.equals("1")){
				order.put("view", Order.DESC);
			}else{
				order.put("createTime", Order.DESC);
			}
		}else{
			order.put("createTime", Order.DESC);
		}
		
		com.aurora.base.dto.QueryResult<Thing> res = this.baseDao.query(request, order, null);
		System.out.println(res.getCount());
		request.setAttribute("count", res.getCount());
		request.setAttribute("isLast", res.isLast());
		return res.getResults();

	}
	
	public List<Thing> searchListWithPages(int pageNum,int pageSize,String searchKey,CategoryThing catagory){
		StringBuilder sb = new StringBuilder();
		List<Object> array = new ArrayList<Object>();
		if(catagory!=null){
			sb.append(" and o.category = ?");
			array.add(catagory);
		}
		if(StringUtils.isNotBlank(searchKey)){
			sb.append(" and (o.title like ? or o.describle like ?)");
			array.add("%"+searchKey+"%");
			array.add("%"+searchKey+"%");
		}
		String sql = sb.toString();
		sql = sql.substring(4,sql.length());
		System.out.println(sql);
		Order order = new Order();
		order.put("createTime", Order.DESC);
		return this.baseDao.list(order,(pageNum-1)*pageSize,pageSize,sql, array.toArray());
	}
	
	/**
	 * 获取用户的发布闲置
	 * @param request
	 * @param userId
	 * @return
	 */
	public List<Thing> getListByUserWithPages(HttpServletRequest request,String userId){
		Order order = new Order();
		order.put("createTime", Order.DESC);
		QueryResult<Thing> res = this.baseDao.query(request, order, "o.user.id = ? and o.isDelete = 0",userId);
		System.out.println(res.getCount());
		request.setAttribute("count", res.getCount());
		return res.getResults();
	}


	/**
	 * 新增一条消息
	 * 方法已废弃
	 * @param params
	 * @throws Exception 
	 */
	@Transactional
	public Thing create(Map<String,String> params,User user) throws Exception {
		System.out.println("saving Thing ....................................");
		// TODO 自动生成的方法存根
		String categoryId = params.get("categoryId");
		String cost = params.get("cost");
		String describle = params.get("describle");
		String images = params.get("images");
		LOG.info(images);
		String newDegree = params.get("newDegree");
		String num = params.get("num");
		String originalCost = params.get("originalCost");
		String outOfTime = params.get("outOfTime");
		String title = params.get("title");
		String phone = params.get("phone");
		String locationId = params.get("location");
		
		CategoryThing categoryThing = this.categoryThingDao.find(categoryId);
		Location location = this.locationDao.find(locationId);
		if(null == categoryThing){
			throw new Exception("the category isn't exist");
		}
		if(null == location){
			throw new Exception("the location isn't exist");
		}
		if(null == phone){
			throw new Exception("the phone can not be empty!!");
		}
		if(null == title){
			throw new Exception("the title can not be empty!!");
		}
		
		//发布数量加一
		user.setIssueNum(user.getIssueNum()+1);
		this.userDao.merge(user);
		
		Thing thing = new Thing();
		thing.setUser(user);
		thing.setCategory(categoryThing);
		thing.setCost(BigDecimal.valueOf(Double.valueOf(cost)));
		thing.setDescrible(describle);
		thing.setPhone(Long.valueOf(phone));
		thing.setNewDegree(Integer.valueOf(newDegree));
		thing.setNum(Integer.valueOf(num));
		thing.setOriginalCost(BigDecimal.valueOf(Double.valueOf(originalCost)));
		thing.setOutOfTime(StringConvertDate.StrToDate(outOfTime));
		thing.setTitle(title);
		thing.setLocation(location);
		this.baseDao.persist(thing);
		
		String[] img = images.split(",");
		for (String url : img) {
			ThingImage image = new ThingImage();
			image.setThing(thing);
			image.setPath(url);
			this.thingImageDao.persist(image);
		}
		
		return thing;
	}
	/**
	 * 新增一条消息
	 * @param params
	 * @throws Exception 
	 */
	@Transactional
	public Thing create2(String categoryId,String cost,String describle,String images,String newDegree,String num,String originalCost,String outOfTime,
			String title,String phone,String locationId,User user) throws Exception {
		System.out.println("saving Thing ....................................");
		
		CategoryThing categoryThing = this.categoryThingDao.find(categoryId);
		Location location = this.locationDao.find(locationId);
		if(null == categoryThing){
			throw new Exception("the category isn't exist");
		}
		if(null == location){
			throw new Exception("the location isn't exist");
		}
		
		//发布数量加一
		user.setIssueNum(user.getIssueNum()+1);
		this.userDao.merge(user);
		
		Thing thing = new Thing();
		thing.setUser(user);
		thing.setCategory(categoryThing);
		thing.setCost(BigDecimal.valueOf(Double.valueOf(cost)));
		thing.setDescrible(describle);
		thing.setPhone(Long.valueOf(phone));
		thing.setNewDegree(Integer.valueOf(newDegree));
		thing.setNum(Integer.valueOf(num));
		thing.setOriginalCost(BigDecimal.valueOf(Double.valueOf(originalCost)));
		thing.setOutOfTime(StringConvertDate.StrToDate(outOfTime));
		thing.setTitle(title);
		thing.setLocation(location);
		this.baseDao.persist(thing);
		
		//生成订单
		PayOrder payOrder = new PayOrder();
		payOrder.setMoney(thing.getCost());
		payOrder.setOrder(UUID.randomUUID().toString());
		payOrder.setState(PayState.PRAPARE);
		payOrder.setThing(thing);
		this.payOrderDao.persist(payOrder);
		
		String[] img = images.split(",");
		for (String url : img) {
			ThingImage image = new ThingImage();
			image.setThing(thing);
			image.setPath(url);
			this.thingImageDao.persist(image);
		}
		
		return thing;
	}

	
	/**
	 * 根据分类获取物品列表
	 * @param categoryId
	 * @param firstResult
	 * @param maxResults
	 * @return
	 */
	public List<Thing> getListByCategoryId(String categoryId,int firstResult,int maxResults){
		return this.baseDao.list(firstResult, maxResults, "o.category.id = ? and o.isDelete = ? ", categoryId,FakeDelete.NODELETE);
	}
	
}
